package com.dragonfly.shutter.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.beans.Message;
import com.dragonfly.shutter.services.DeletePictureService;
import com.dragonfly.shutter.utils.KeywordFilter;

/**
 * 删除图片控制类
 * @author 黄挺
 *
 */
@Controller
@RequestMapping("/deletePicture.html")
public class DeletePictureController {
	@Autowired 
	private DeletePictureService deletePictureService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(@RequestParam(value="pictureID", required=false) String pictureID,
			@RequestParam(value="ownerID",required=false) String ownerIDStr,
			HttpServletRequest request, HttpSession session,
			ModelMap model){
		Message message = null;
		
		//图片不存在
		if(pictureID == null || ownerIDStr == null ){
			message = new Message("空的参数", "操作失败", "/Dragonfly");
			return new ModelAndView("message", "message", message);
		}
		
		//非法的参数(要求为全数值型)
		if( !KeywordFilter.isNumeric(ownerIDStr) || !KeywordFilter.isNumeric(pictureID)){
			message = new Message("非法的参数", "操作失败", "/Dragonfly");
			return new ModelAndView("message", "message", message);
		}
			
		Integer ownerID = Integer.parseInt(ownerIDStr);
		Integer userID = (Integer) session.getAttribute("userID");
		
		//用户权限不够
		if(userID == null || userID != ownerID) {
			message = new Message("您不是这张图片的所有者，无法删除", "操作失败", "/Dragonfly/picture.html?pictureID=" + pictureID);
			return new ModelAndView("message", "message", message);
		}
		
		try {
			deletePictureService.doService(pictureID, request.getRequestURL().toString());
		} catch (Exception e) {
			//要删除的图片不存在
			e.printStackTrace();
			message = new Message(e.getMessage(), "操作失败", "/Dragonfly");
			return new ModelAndView("message", "message", message); 
		}
		model.remove("picture");
		return new ModelAndView("redirect:/album.html?albumID="+(Integer)session.getAttribute("albumID"));
	}
}
